import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import router from '../router';
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);

const instanceAxios=axios.create({
  baseURL: "http://39.106.207.193:3000/",
  headers:{
    "Accept": "*/*",
  },
  responseType: "json",
  timeout: 3000
});

function handleRequestSuccess(config: AxiosRequestConfig){
  // 在发送请求之前做些什么
  const token=localStorage.getItem("access_token");
  if(token){
    config.headers['Authorization']=` Bearer ${token}`;
  }
  return config;
}

function handleRequestError(error){
  // 对请求错误做些什么
  return Promise.reject(error);
}

function handleResponseSuccess(response: AxiosResponse){
  // 对响应数据做点什么
  //console.log(response);
  return response
}

function handleResponseError(error){
  // 对响应错误做点什么
  //console.log(error.response);
  const code=error.response.status;
  switch(code){
    case 401:
      console.error(`${error.response.config.baseURL}${error.response.config.url} `+error.message);
      if(router.currentRoute.fullPath!="/login"){
        router.push({
          path:'/login',
          query:{
            cb_path: router.currentRoute.fullPath
          }
        });
      }
      break;
    case 429:
      console.error(`${error.response.config.baseURL}${error.response.config.url} `+error.message);
      Toast.fail('Too Many Requests');
      break;
  }
  return Promise.reject(error);
}

instanceAxios.interceptors.request.use(handleRequestSuccess,handleRequestSuccess);
instanceAxios.interceptors.response.use(handleResponseSuccess,handleResponseError);

export default instanceAxios;